<template>
  <el-main>
    <h1 style="margin-bottom: 20px">{{ this.id ? '编辑管理员' : '新建管理员'}}</h1>
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="用户名">
            <el-input v-model="form.username"></el-input>
        </el-form-item>

        <el-form-item label="密码">
          <el-input v-model="form.password"></el-input>
        </el-form-item>
        
        <el-form-item>
            <el-button type="primary" @click="onSubmit">保存</el-button>
            <el-button>取消</el-button>
        </el-form-item>
      </el-form>
    </el-main>
</template>
<script>
  export default {
    props: {
      id: {type: String}
    },
    data() {
      return {
        form: {
          username: '',
          password: '',
        },
      }
    },
    created() {
      this.id && this.fetch()
    },
    methods: {
      async onSubmit() {
        let res
        if(this.id) {
          res = await this.$http.put(`curd/adminuser/${this.id}`, this.form)
        } else {
          res = await this.$http.post('curd/adminuser', this.form)
        }
        if(res.data.code === 200) {
          this.$message({
            message: '保存成功！',
            type: 'success'
          });
          this.$router.push('/adminuser/list')
        }
      },
      async fetch() {
        const res = await this.$http.get(`curd/adminuser/${this.id}`)
        this.form = res.data
      },
    }
  }
</script>